//
//  CollectionView.swift
//  MYModule
//
//  Created by 李然 on 2022/7/19.
//

import UIKit

open class CollectionView: UICollectionView {
    
    
    /// 是否自动适应 contentSize 调整自动布局宽高
   public var automaticallyContentSize: Bool = false


    public init() {
        super.init(frame: CGRect(), collectionViewLayout: UICollectionViewFlowLayout())
        makeUI()
    }

    public override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        makeUI()
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        makeUI()
    }

    open func makeUI() {
        self.layer.masksToBounds = true
        self.backgroundColor = .clear
        updateUI()
    }

    open func updateUI() {
        setNeedsDisplay()
    }

    public func itemWidth(forItemsPerRow itemsPerRow: Int, withInset inset: CGFloat = 0) -> CGFloat {
        let collectionWidth = Int(frame.size.width)
        if collectionWidth == 0 {
            return 0
        }
        return CGFloat(Int((collectionWidth - (itemsPerRow + 1) * Int(inset)) / itemsPerRow))
    }

    public func setItemSize(_ size: CGSize) {
        if size.width == 0 || size.height == 0 {
            return
        }
        let layout = (self.collectionViewLayout as? UICollectionViewFlowLayout)!
        layout.itemSize = size
    }
    
    
    open override var contentSize: CGSize {
        
        didSet {
           
            if !automaticallyContentSize {
                return
            }
        
            invalidateIntrinsicContentSize()
        }
    }
    
    open override var intrinsicContentSize: CGSize {
      var size = super.intrinsicContentSize
        if !automaticallyContentSize {
            return size
        }
        
        layoutIfNeeded()
        size = CGSize(width: UIView.noIntrinsicMetric, height: contentSize.height)
        return size
        
    }
    
}
